package com.github.soiff.shadow.autoconfigure;

import com.github.jknack.handlebars.Handlebars;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * Created by Soiff on 2016/05/23.
 *
 * @author : Soiff
 */
@Controller
public class SoiffShadowController {

    final static Splitter COLON = Splitter.on(":").omitEmptyStrings().trimResults();

    @Autowired
    private Handlebars handlebars;
    @Autowired
    private ApplicationContext context;

    @RequestMapping
    public void doRequest(HttpServletRequest request, HttpServletResponse response, Map<String, Object> context) throws IOException {
        String domain = (String)request.getAttribute("DOMAIN");
        if (null == domain)
            domain = COLON.splitToList(request.getHeader("Host")).get(0);
        if(!domain.equals("localhost") && !domain.equals("127.0.0.1")) {
            //TODO: add proper license logical.
            throw new RuntimeException("No valid license found!");
        }

        String path = request.getRequestURI().substring(request.getContextPath().length() + 1);
        if(Strings.isNullOrEmpty(path)) {
            path = "index.hbs";
        }

        handlebars.compile(path).apply(context, response.getWriter());
    }
}
